<script setup>
import { ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Message,Modal } from '@arco-design/web-vue'
import api from '@/api'

const switchValue = ref('')
const $route = useRoute()
const $router = useRouter()

const keyword = ref('')
const keyword2 = ref('')
const listData = ref([])
const userData = ref([])
const courseData = ref([])
const taskData = ref([])
let cl=[...new Set(courseData.value)];
const getListData = async () => {
  try {
    const res = await api.get('/group/mygroup', {
      params: {
        keyword: keyword.value,
        page: 1,
        pageSize: 10,
      },
    })
    console.log('res', res)
    listData.value = res.data
    // listTotal.value = res.total
  } catch (error) {
    console.error(error)
  }
}
getListData()
const getUserData = async (group_id) => {
  try {
    const res = await api.get('/group/group_user', {
      params: {
        group_id: group_id,
        page: 1,
        pageSize: 10,
      },
    })
    console.log('res', res)
    userData.value = res.data.items
    // listTotal.value = res.total
  } catch (error) {
    console.error(error)
  }
}
const getCourseData = async () => {
  try {
    const res = await api.get('/courses/options', {
    })
    console.log('res', res)
    courseData.value = res
    cl=[...new Set(courseData.value)];
    // listTotal.value = res.total
  } catch (error) {
    console.error(error)
  }
}
getCourseData()

const getTaskData = async (group_id) => {
  try {
    if(group_id==0){
      group_id = formData2.value.group_id
    }
    const res = await api.get('/group/group_task', {
      params: {
        group_id: group_id,
        keyword: keyword2.value,
        page: 1,
        pageSize: 10,
      },
    })
    console.log('res', res)
    taskData.value = res.data.items
    // listTotal.value = res.total
  } catch (error) {
    console.error(error)
  }
}

const formVisible = ref(false)
const formVisible2 = ref(false)
const formVisible3 = ref(false)
const formLoading = ref(false)
const formRef = ref()
const formItem = ref(null)
const formItem2 = ref(null)
const formData2 = ref({
  group_id: '',
  name: '',
  type: '',
  content_id: '',
  start_time: '',
  end_time: '',
})
const formRules = {
  name: [
    {
      required: true,
      message: '请填写任务名称',
    },
  ],
  type: [
    {
      required: true,
      message: '请选择任务类型',
    },
  ],
  content_id: [
    {
      required: true,
      message: '请选择任务内容',
    },
  ],
  start_time: [
    {
      required: true,
      message: '请选择开始时间',
    },
  ],
  end_time: [
    {
      required: true,
      message: '请选择结束时间',
    },
  ],
}

const doimport = (record) => {
  getUserData(record.id)
  formVisible.value = true
  formItem.value = record.id
}

const setTask = (record) => {
  getTaskData(record.id)
  formVisible2.value = true
  formData2.value.group_id = record.id
}

const create = () => {
  formRef.value?.resetFields()
  formItem2.value = null
  formVisible3.value = true
}

const download = () => {
  let a=document.createElement("a");
  a.href="/template/group_user.xlsx";
  a.download="群组成员导入模板";
  a.style.display='none';
  document.body.appendChild(a);
  a.click();
  a.remove();
}

const doupload = (option) => {
  console.log(option)
  const {fileItem} = option
  const formData = new FormData();
  formData.append('file', fileItem.file);
  formData.append('id', formItem.value);
  api.post('/group/import_user', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
  .then((res) => {
    if (res.code == 200) {
      Message.success({
        content: '上传成功',
      })
      getUserData(formItem.value)
    } else {
      Message.error({
        content: res.message,
      })
    }
  })
}
const delGroupUser = (record) => {
  // Message.error({
  //   content: record.id,
  // })
  api
    .delete(`/group/group_user/${record.id}`)
    .then((res) => {
      if (res.code == 200) {
        Message.success({
          content: '删除成功',
        })
        getUserData(record.group_id)
      } else {
        Message.error({
          content: res.message,
        })
      }
    })
}

const toJump = (url) => {
  console.log('router', $router.push(url))
  $router.push(url)
}

const formSubmit = async () => {
  if (await formRef.value.validate()) {
    return false
  }
  formLoading.value = true
  try {
    await api.post('group/add_task', formData2.value)
    formRef.value?.resetFields()
    formVisible3.value = false
    getTaskData(0)
  } catch (error) {
    console.error(error)
  }
  formLoading.value = false
  return false
}

const pushTask = (record) => {
  if(typeof record.is_pushed=='number')return;
  api
    .post(`/group/push_task`,{id:record.id,pushed:record.is_pushed})
    .then((res) => {
      if (res.code == 200) {
        Message.success({
          content: '操作成功',
        })
      } else {
        Message.error({
          content: res.message,
        })
      }
    })
}
const delTask = (record) => {
  let group_id=record.group_id
  Modal.confirm({
    title: '删除',
    content: '您确定要删除吗？',
    bodyStyle: 'text-align:center',
    onBeforeOk: async () => {
      await api.delete(`/group/del_task/${record.id}`)
      getTaskData(group_id)
    },
  })
}
</script>

<template>
  <div class="page">
    <div class="header">
      <div>
        <a-input-search
          :style="{ width: '320px' }"
          v-model="keyword"
          placeholder="群组名称模糊查询"
          button-text="查询"
          @search="getListData"
          search-button
        />
      </div>
    </div>

    <a-table :data="listData">
      <template #columns>
        <a-table-column title="序号" :width="60">
          <template #cell="{ rowIndex }"> {{ rowIndex + 1 }} </template>
        </a-table-column>
        <a-table-column
          title="群组名称"
          data-index="name"
        ></a-table-column>
        <a-table-column
          title="人数"
          data-index="users_count"
        ></a-table-column>
        <a-table-column
          title="任务数"
          data-index="tasks_count"
        ></a-table-column>
        <a-table-column title="操作" align="center" :width="300">
          <template #cell="{ record }">
            <a-space>
              <a-button
                type="primary"
                size="mini"
                @click="setTask(record)"
                >配置任务</a-button
              >
              <a-button
                type="primary"
                size="mini"
                @click="doimport(record)"
                >导入人员</a-button
              >
            </a-space>
          </template>
        </a-table-column>
      </template>
    </a-table>

    <a-modal
      v-model:visible="formVisible"
      title="导入成员"
      :ok-loading="formLoading"
      :hideCancel="true"
      okText="关闭"
    >
      <div class="header">
        <a-button @click="download" type="primary"
          >下载模板</a-button
        >
        &nbsp;&nbsp;&nbsp;&nbsp;
        <a-upload :custom-request="doupload" :show-file-list="false">
          <template #upload-button>
            <a-button type="primary"
              >导入人员</a-button
            >
          </template>
        </a-upload>
      </div>

      <a-table :data="userData">
        <template #columns>
          <a-table-column title="序号" :width="60">
            <template #cell="{ rowIndex }"> {{ rowIndex + 1 }} </template>
          </a-table-column>
          <a-table-column
            title="姓名"
          >
            <template #cell="{ record }">
              {{record.user.name}}
            </template>
          </a-table-column>
          <a-table-column
            title="手机号"
          >
            <template #cell="{ record }">
              {{record.user.username}}
            </template>
          </a-table-column>

          <a-table-column title="操作" align="center" :width="100">
            <template #cell="{ record }">
              <a-space>
                <a-button
                  type="primary"
                  status="danger"
                  size="mini"
                  @click="delGroupUser(record)"
                  >移除</a-button
                >
              </a-space>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-modal>

    <a-modal
      v-model:visible="formVisible2"
      title="配置任务"
      :ok-loading="formLoading"
      :hideCancel="true"
      okText="关闭"
      width="auto"
    >
      <div class="header">
        <div>
          <a-input-search
            :style="{ width: '320px' }"
            v-model="keyword2"
            placeholder="任务模糊查询"
            button-text="查询"
            @search="getTaskData(0)"
            search-button
          />
        </div>
        <a-button @click="create" type="primary"
          >新建任务</a-button
        >
      </div>

      <a-table :data="taskData">
        <template #columns>
          <a-table-column title="序号" :width="60">
            <template #cell="{ rowIndex }"> {{ rowIndex + 1 }} </template>
          </a-table-column>
          <a-table-column
            title="名称"
          >
            <template #cell="{ record }">
              {{record.name}}
            </template>
          </a-table-column>
          <a-table-column
            title="任务类型"
          >
            <template #cell="{ record }">
              <span v-if="record.type==1">学习课程</span>
            </template>
          </a-table-column>
          <a-table-column
            title="任务开始时间"
            data-index="start_time"
          ></a-table-column>
          
          <a-table-column
            title="任务结束时间"
            data-index="end_time"
          ></a-table-column>
          <a-table-column
            title="推送"
          >
            <template #cell="{ record }">
              <a-switch v-model="record.is_pushed" @click="pushTask(record)"/>
            </template>
          </a-table-column>

          <a-table-column title="操作" align="center" :width="100">
            <template #cell="{ record }">
              <a-space>
                <a-button
                  type="primary"
                  status="danger"
                  size="mini"
                  @click="delTask(record)"
                  >删除</a-button
                >
              </a-space>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-modal>

    <a-modal
      v-model:visible="formVisible3"
      title="新建任务"
      :ok-loading="formLoading"
      :on-before-ok="formSubmit"
    >
      <a-form ref="formRef" :model="formData2" :rules="formRules">
        <a-form-item field="name" label="任务名称">
          <a-input v-model="formData2.name" allow-clear />
        </a-form-item>
        <a-form-item field="type" label="任务类型">
          <a-select v-model="formData2.type" :style="{width:'320px'}" placeholder="请选择任务类型">
            <a-option value="1">
              学习课程
            </a-option>
          </a-select>
        </a-form-item>
        <a-form-item field="content_id" label="任务内容">
          <a-select v-model="formData2.content_id" :style="{width:'320px'}" placeholder="请选择内容" allow-search>
            <a-option
              v-for="item in cl"
              :value="item.id"
            >
            {{item.name}}
            </a-option>
          </a-select>
        </a-form-item>
        <a-form-item field="start_time" label="开始时间">
          <a-date-picker
            style="width: 220px; margin: 0 24px 24px 0;"
            show-time
            format="YYYY-MM-DD HH:mm:ss"
            v-model="formData2.start_time"
          />
        </a-form-item>
        <a-form-item field="end_time" label="结束时间">
          <a-date-picker
            style="width: 220px; margin: 0 24px 24px 0;"
            show-time
            format="YYYY-MM-DD HH:mm:ss"
            v-model="formData2.end_time"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<style scoped>
.page {
  height: 100%;
}

.header {
  height: 52px;
  display: flex;
  justify-content: space-between;
}
</style>
